<?php
// 启用错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// 增加内存限制和执行时间
ini_set('memory_limit', '1024M');  // 设置为1GB
ini_set('max_execution_time', 600); // 设置为10分钟
ini_set('post_max_size', '512M');
ini_set('upload_max_filesize', '512M');

// 设置错误处理
function handleError($errno, $errstr, $errfile, $errline) {
    error_log("Error ($errno): $errstr in $errfile on line $errline");
    http_response_code(500);
    echo json_encode(['error' => '服务器处理错误']);
    exit;
}
set_error_handler('handleError');

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key, X-Request-Timestamp');

// 增加响应超时时间
set_time_limit(600);

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 配置
define('API_KEY', 'axure-sync-2024');

// 验证请求
$headers = getallheaders();
$apiKey = isset($headers['X-Api-Key']) ? $headers['X-Api-Key'] : 
          (isset($headers['x-api-key']) ? $headers['x-api-key'] : '');
$timestamp = isset($headers['X-Request-Timestamp']) ? $headers['X-Request-Timestamp'] : '';

// 调试信息
error_log("Received API Key: " . $apiKey);
error_log("Expected API Key: " . API_KEY);
error_log("Request Headers: " . print_r($headers, true));

// 验证API密钥
if ($apiKey !== API_KEY) {
    http_response_code(403);
    echo json_encode([
        'error' => '无效的API密钥',
        'debug' => [
            'received' => $apiKey,
            'expected' => API_KEY,
            'headers' => $headers
        ]
    ]);
    exit;
}

// 接收POST数据
$json = file_get_contents('php://input');
$jsonError = json_last_error();
if ($jsonError !== JSON_ERROR_NONE) {
    error_log("JSON decode error: " . json_last_error_msg());
    http_response_code(400);
    echo json_encode(['error' => '无效的数据格式: ' . json_last_error_msg()]);
    exit;
}

$data = json_decode($json, true);
if ($data === null) {
    error_log("Failed to decode JSON data. Raw input: " . substr($json, 0, 1000) . "...");
    http_response_code(400);
    echo json_encode(['error' => '数据解析失败']);
    exit;
}

$uploadDir = trim($data['uploadDir']);

// 验证上传目录
if (empty($uploadDir)) {
    http_response_code(400);
    echo json_encode(['error' => '上传目录不能为空']);
    exit;
}

// 清理目录名，只允许字母、数字、下划线和横杠
$uploadDir = preg_replace('/[^a-zA-Z0-9_-]/', '', $uploadDir);

// 确保uploads目录存在且有正确的权限
$uploadsDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads';
$projectDir = $uploadsDir . '/' . $uploadDir;

// 如果目录已存在，删除旧文件
if (file_exists($projectDir)) {
    try {
        // 递归删除目录
        function deleteDirectory($dir) {
            if (!file_exists($dir)) return true;
            if (!is_dir($dir)) return unlink($dir);
            foreach (scandir($dir) as $item) {
                if ($item == '.' || $item == '..') continue;
                if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) return false;
            }
            return rmdir($dir);
        }
        deleteDirectory($projectDir);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => '无法删除旧文件']);
        exit;
    }
}

// 创建项目目录
if (!file_exists($projectDir)) {
    try {
        if (!mkdir($projectDir, 0755, true)) {
            throw new Exception('无法创建项目目录');
        }
        chmod($projectDir, 0755);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => '服务器错误：' . $e->getMessage()]);
        exit;
    }
}

// 在保存资源文件之前，确保所有必要的目录都存在
$requiredDirs = [
    $projectDir . '/resources/scripts/axure',
    $projectDir . '/resources/css',
    $projectDir . '/resources/images',
    $projectDir . '/plugins/sitemap/styles/images',
    $projectDir . '/plugins/page_notes/styles/images',
    $projectDir . '/plugins/debug/styles/images',
    $projectDir . '/data',
    $projectDir . '/files'
];

foreach ($requiredDirs as $dir) {
    if (!file_exists($dir)) {
        mkdir($dir, 0755, true);
        chmod($dir, 0755);
    }
}

// 在保存资源文件之前，添加favicon
$requiredDirs[] = $projectDir . '/resources/images';

// 复制favicon文件
$faviconFiles = [
    'favicon_play.ico',
    'favicon_play.svg'
];

foreach ($faviconFiles as $favicon) {
    $source = __DIR__ . '/resources/images/' . $favicon;
    $dest = $projectDir . '/resources/images/' . $favicon;
    if (file_exists($source)) {
        copy($source, $dest);
    }
}

// 保存资源文件
$mainFilePath = '';
$indexHtml = $data['html'];
$totalFiles = count($data['resources']);
$currentFile = 0;

foreach ($data['resources'] as $resource) {
    $resourcePath = $projectDir . '/' . trim($resource['path'], '/');
    
    // 创建目录结构
    $dir = dirname($resourcePath);
    try {
        if (!file_exists($dir)) {
            if (!mkdir($dir, 0755, true)) {
                throw new Exception('无法创建目录：' . $dir);
            }
            chmod($dir, 0755);
        }
        
        // 更新进度
        $currentFile++;
        $progress = [
            'current' => $currentFile,
            'total' => $totalFiles,
            'file' => basename($resourcePath)
        ];
        
        if (!empty($resource['isMainFile'])) {
            // 保存主文件
            if (file_put_contents($resourcePath, $indexHtml) === false) {
                throw new Exception('无法保存主文件');
            }
            chmod($resourcePath, 0644);
            
            if (!empty($resource['isMainPage'])) {
                $mainFilePath = $resourcePath;
            }
        } else {
            // 处理其他资源文件
            $content = !empty($resource['isBase64']) 
                ? base64_decode(preg_replace('#^data:.*?;base64,#', '', $resource['content']))
                : $resource['content'];
            
            if (file_put_contents($resourcePath, $content) === false) {
                throw new Exception('无法保存资源文件：' . $resourcePath);
            }
            chmod($resourcePath, 0644);
        }
        
        // 每保存10个文件刷新一次输出缓冲
        if ($currentFile % 10 === 0) {
            flush();
            ob_flush();
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => '保存文件失败：' . $e->getMessage()]);
        exit;
    }
}

// 保存index.html
$indexPath = $projectDir . '/index.html';
copy($projectDir . '/start.html', $indexPath);

// 验证文件是否成功创建和可访问
$indexPath = $projectDir . '/index.html';
if (!file_exists($indexPath)) {
    http_response_code(500);
    echo json_encode(['error' => '文件创建失败']);
    exit;
}

if (!is_readable($indexPath)) {
    http_response_code(500);
    echo json_encode(['error' => '文件无法访问']);
    exit;
}

// 验证文件大小
$fileSize = filesize($indexPath);
if ($fileSize === 0) {
    http_response_code(500);
    echo json_encode(['error' => '文件内容为空']);
    exit;
}

// 生成预览URL
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
// 获取相对于网站根目录的路径
$relativePath = str_replace($_SERVER['DOCUMENT_ROOT'], '', $projectDir);
$previewUrl = $protocol . $_SERVER['HTTP_HOST'] . '/' . ltrim($relativePath, '/') . '/';
if ($mainFilePath) {
    $previewUrl .= basename($mainFilePath);
} else {
    $previewUrl .= 'index.html';
}


// 返回成功响应
echo json_encode([
    'success' => true,
    'previewUrl' => $previewUrl,
    'message' => '上传成功',
    'progress' => [
        'current' => $currentFile,
        'total' => $totalFiles
    ],
    'debug' => [
        'documentRoot' => $_SERVER['DOCUMENT_ROOT'],
        'projectDir' => $projectDir,
        'relativePath' => $relativePath
    ]
]);
?> 